import strip from 'strip-comments';

import {
  INCLUDE_TAG,
  EXCLUDE_TAG,
  END_TAG,
  logWarn
} from '@shared';
// 条件编译
const includePattern = /\/\/(?:\s+)?#ifdef([A-Z\d\-\|\s]+)/g;
const excludePattern = /\/\/(?:\s+)?#ifndef([A-Z\d\-\|\s]+)/g;
const endPattern = /\/\/(?:\s+)?#endif/g;
// 不支持转换的条件编译
// const ifdefProp = /\/\/(?:\s+)?#ifdef[A-Z\d\-\|\s]+(,)?"/g;
// const ifndefProp = /\/\/(?:\s+)?#ifndef[A-Z\d\-\|\s]+(,)?"/g;
const endifProp = /"(,)?(?:[\s\t\n]+)?\/\/(?:\s+)?#endif/g;
// 其他
const fontTextPattern = /"(\\u[a-z0-9]+)/g;
const subpackgesPattern = /"subPackages"/;
// main
export default function optimizePagesJson(pagesJsonString) {
  // 提示或者忽略无法处理的注释情况
  const unsupported = pagesJsonString.match(endifProp);
  if (unsupported) {
    // 这里提示一下不支持
    logWarn('pages.json 中存在不支持转换的条件编译信息');
    return;
    //TODO 把不支持的条件编译信息移除，生成的数据会有问题，是否有办法转换？
    // pagesJsonString = pagesJsonString
    //   .replace(ifdefProp, '$1"')
    //   .replace(ifndefProp, '$1"')
    //   .replace(endifProp, '"$1');
  }
  // include
  pagesJsonString = pagesJsonString.replace(includePattern, function(matches, $1) {
    return ',{"' + INCLUDE_TAG + '": "' + $1.replace(/\s+/g, '') + '"},';
  });
  // exclude
  pagesJsonString = pagesJsonString.replace(excludePattern, function(matches, $1) {
    return ',{"' + EXCLUDE_TAG + '": "' + $1.replace(/\s+/g, '') + '"},';
  });
  // end
  pagesJsonString = pagesJsonString.replace(endPattern, ',{"' + END_TAG + '": true},');
  // 注释以及多余的符号
  pagesJsonString = strip(pagesJsonString)
    .replace(/\s+/g, '')
    .replace(/,,/g, ',')
    .replace(/,\]/g, ']');
  // 主要处理 buttons 中的 text 字符，'\ue123' 应当转换为 '\\ue123'，否则会被转义进而丢失字符串信息。
  pagesJsonString = pagesJsonString.replace(fontTextPattern, `"\\$1`);
  // 使用 subpackages 规范
  pagesJsonString = pagesJsonString.replace(subpackgesPattern, '"subpackages"');

  return pagesJsonString;
}
